package com.sskj.lib.ui.activity;


import android.Manifest;
import android.content.Intent;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.PermissionTipUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.R;
import com.sskj.lib.R2;
import com.sskj.lib.RConfig;
import com.sskj.lib.bean.AddressBean;
import com.sskj.lib.bean.ScanBean;
import com.sskj.lib.presenter.ScanActivityPresenter;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.util.QRCodeUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

@Route(path = RConfig.LIB_SCAN)
public class ScanActivity extends BaseActivity<ScanActivityPresenter> implements QRCodeView.Delegate {
    @BindView(R2.id.mZXingView)
    ZXingView mZXingView;
    @BindView(R2.id.tvChoose)
    TextView tvChoose;
    private String mImagePath;
    @Autowired
    boolean isShow=false;

    @Override
    protected int getLayoutId() {
        return R.layout.lib_activity_scan;
    }

    @Override
    public ScanActivityPresenter getPresenter() {
        return new ScanActivityPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        mZXingView.setDelegate(this);
        setTitle("二维码扫描");
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA)
                .subscribe(isGrant -> {
                    if (isGrant) {
                        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

                        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                    } else {
                        PermissionTipUtil.tip(this, "拍照");
                    }
                });
        ClickUtil.click(tvChoose, () -> {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .selectionMode(PictureConfig.SINGLE)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mZXingView==null)
            return;
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mZXingView==null)
            return;
        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia media = selectList.get(0);
                    if (media.isCompressed()) {
                        mImagePath = media.getCompressPath();
                    } else {
                        mImagePath = media.getPath();
                    }

                    QRCodeUtil.analyzeBitmap(mImagePath, new QRCodeUtil.OnAnalyzeCallback() {
                        @Override
                        public void onAnalyzeSuccess(String content) {
                            if (isShow) {
                                ARouter.getInstance().build(RConfig.WALLET_SCAN_RESULT).withString(Constans.ADDRESS, content).navigation();
                            }else {
                                RxBus.getDefault().post(new ScanBean(content));
                            }
                            finish();
                        }

                        @Override
                        public void onAnalyzeFailed() {
                            ToastUtil.showShort("识别失败");

                        }
                    });

                    break;
            }

        }
    }

    @Override
    public void onScanQRCodeSuccess(String content) {
        vibrate();
        if (isShow) {
            ARouter.getInstance().build(RConfig.WALLET_SCAN_RESULT).withString(Constans.ADDRESS, content).navigation();
        }else {
            RxBus.getDefault().post(new ScanBean(content));
        }
        finish();


//        mZXingView.startSpot(); // 开始识别
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        ToastUtil.showShort("扫描失败");
    }

}
